/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.insurance.cis.views;

import com.insurance.cis.daos.CategoryDao;
import com.insurance.cis.daos.ProductDao;
import com.insurance.cis.models.Product;
import com.insurance.cis.models.ProductCategory;
import com.insurance.cis.scos.ProductSearchCondition;
import com.insurance.cis.utils.MessageDialogUtils;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author TruongLQ
 */
public class ProductJDialogChooser extends javax.swing.JDialog {

    DefaultTableModel dtm;
    ProductDao productDao = new ProductDao();
    MainJFrameView mainJFrame;
    CategoryDao categoryDao = new CategoryDao();
    CampaignJDialogCreationView campaignJDialogView;
    CampaignJDialogUpdateView campaignJDialogUpdateView;
    JPanel fromJpnl;
    
    /**
     * Creates new form ProductJDialogChooser
     */
    public ProductJDialogChooser(java.awt.Frame parent, boolean modal, JPanel fromJPanel) {
        super(parent, modal);
        initComponents();
        loadTableMetaData();
        mainJFrame = (MainJFrameView) parent;
        this.fromJpnl= fromJPanel;
        loadCategories();
        this.setResizable(false);
        this.setLocationRelativeTo(getRootPane());
    }
    
    public ProductJDialogChooser(CampaignJDialogCreationView parent, boolean modal) {
        super(parent, modal);
        initComponents();
        loadTableMetaData();
        campaignJDialogView = parent;
        loadCategories();
        this.setResizable(false);
        this.setLocationRelativeTo(getRootPane());
    }
    
    public ProductJDialogChooser(CampaignJDialogUpdateView parent, boolean modal) {
        super(parent, modal);
        initComponents();
        loadTableMetaData();
        campaignJDialogUpdateView = parent;
        loadCategories();
        this.setResizable(false);
        this.setLocationRelativeTo(getRootPane());
    }

    private void loadCategories() {
        Vector<ProductCategory> categories = categoryDao.getAllProductCategories();
        categories.add(0, new ProductCategory(null, "Select a category"));
        cbxProductCategory.setModel(new DefaultComboBoxModel(categories));
    }

    private void loadTableMetaData() {
        Vector colHeader = new Vector(4);
        colHeader.add("Product ID");
        colHeader.add("Product Name");
        colHeader.add("Product Category");
        colHeader.add("Product Description");
        dtm = new DefaultTableModel(colHeader, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tblProductResult.setModel(dtm);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblProductResult = new javax.swing.JTable();
        btnChooseItem = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtProductID = new javax.swing.JTextField();
        txtProductName = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        cbxProductCategory = new javax.swing.JComboBox();
        btnClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Product Chooser Dialog");

        tblProductResult.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblProductResult);

        btnChooseItem.setText("Choose being selected item");
        btnChooseItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseItemActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED), "Search criteria", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12)))); // NOI18N

        jLabel1.setText("Product ID");

        jLabel2.setText("Product Name");

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        jLabel4.setText("Product Category");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtProductID, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtProductName, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(33, 33, 33)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(cbxProductCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtProductID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(9, 9, 9)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtProductName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbxProductCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnSearch)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnChooseItem)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap(44, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnChooseItem)
                    .addComponent(btnClose))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnChooseItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseItemActionPerformed
        int row = tblProductResult.getSelectedRow();
        if (row <0 || row >= tblProductResult.getRowCount()) {
            MessageDialogUtils.dialogError(this, "You must choose one item to proceed!");
            return;
        }
        if (mainJFrame!=null) {
            if (fromJpnl instanceof CampaignMasterJPanelView) {
                mainJFrame.getCampaignMasterJpnl().getTxtProductID().setText(
                dtm.getValueAt(tblProductResult.getSelectedRow(), 0).toString());
            } else if (fromJpnl instanceof EstimatedCampaignJPanelView) {
                 mainJFrame.getEstimatedCampaignJpnl().getTxtProductID().setText(
                dtm.getValueAt(tblProductResult.getSelectedRow(), 0).toString());
            } else if (fromJpnl instanceof ActualCampaignJPanelView) {
                mainJFrame.getActualCampaignJpnl().getTxtProductID().setText(
                dtm.getValueAt(tblProductResult.getSelectedRow(), 0).toString());
            }
           
        } else if (campaignJDialogView!=null) {
            campaignJDialogView.getTxtProductID().setText(
                dtm.getValueAt(tblProductResult.getSelectedRow(), 0).toString());
        } else if (campaignJDialogUpdateView!=null) {
            campaignJDialogUpdateView.getTxtProductID().setText(
                dtm.getValueAt(tblProductResult.getSelectedRow(), 0).toString());
        }
        this.dispose();
    }//GEN-LAST:event_btnChooseItemActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        List<Product> products = productDao.getProducts(
                new ProductSearchCondition(txtProductID.getText().trim(),
                txtProductName.getText().trim(),
                ((ProductCategory) cbxProductCategory.getSelectedItem()).getId()));
        if (!products.isEmpty()) {
            loadResults(products);
        } else {
            MessageDialogUtils.dialogMessage(this, "No products found");
            dtm.getDataVector().clear();
            tblProductResult.updateUI();
        }
    }//GEN-LAST:event_btnSearchActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void loadResults(List<Product> products) {
        dtm.getDataVector().clear();
        for (Product product : products) {
            dtm.addRow(new Object[]{product.getId(),
                        product.getName(), product.getCategory().toString(),
                        product.getDesc()});
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnChooseItem;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnSearch;
    private javax.swing.JComboBox cbxProductCategory;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblProductResult;
    private javax.swing.JTextField txtProductID;
    private javax.swing.JTextField txtProductName;
    // End of variables declaration//GEN-END:variables
}
